import datetime
import json

from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer
from Function import set_market_model

import GlobalParam
import LogUtil


class SimpleWS(WebSocket):

    def handleMessage(self):
        try:
            if self.data is not None:
                data = json.loads(self.data)
                msgType = data['msg_type']  # 1:连接第一个包   2：心跳包  3：查询包
                self.label = data['label']
                if 1 == msgType:
                    if self.label in GlobalParam.ws_dic:
                        GlobalParam.ws_dic[self.label].close()
                        GlobalParam.wss.remove(GlobalParam.ws_dic[self.label])
                    GlobalParam.ws_dic[self.label] = self
                    GlobalParam.wss.append(self)
                elif 3 == msgType:
                    ticker_label = data['label']
                    ticker_list = ticker_label.split(',')
                    for ticker in ticker_list:
                        pDepthMarketData = set_market_model(ticker)
                        if pDepthMarketData is not None:
                            self.sendMessage(json.dumps(pDepthMarketData))
                else:
                    self.activetime = datetime.datetime.now()
                    self.sendMessage(json.dumps(data))
        except Exception as e:
            LogUtil.timePrintLog("error：" + e.__str__())

    def handleConnected(self):
        print(self.address, 'connected')

    def handleClose(self):
        print(self.address, 'closed')


def marketData2dict(pDepthMarketData):
    return {
        'InstrumentID': pDepthMarketData.InstrumentID,
        'TradingDay': pDepthMarketData.TradingDay,
        'ExchangeID': pDepthMarketData.ExchangeID,
        'BidPrice1': pDepthMarketData.BidPrice1,
        'AskPrice1': pDepthMarketData.AskPrice1,
        'HighestPrice': pDepthMarketData.HighestPrice,
        'LowestPrice': pDepthMarketData.LowestPrice,
        'LastPrice': pDepthMarketData.LastPrice,
        'OpenPrice': pDepthMarketData.OpenPrice,
        'ClosePrice': pDepthMarketData.ClosePrice,
        'UpperLimitPrice': pDepthMarketData.UpperLimitPrice,
        'LowerLimitPrice': pDepthMarketData.LowerLimitPrice
    }


def startWbSocket():
    try:
        server = SimpleWebSocketServer('', GlobalParam.wss_port, SimpleWS)
        LogUtil.timePrintLog("websocket服务开始启动,端口号：" + str(GlobalParam.wss_port))
        server.serveforever()
    except Exception as e:
        LogUtil.timePrintLog("websocket服务启动失败：" + e.__str__())
